
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package RoomPanel.userInfo;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import players.PlayersEnum;

/**
 *
 * @author 52194291
 */
public class DisplayUserInfo extends HttpServlet {

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     * 
     * url: https://cs4280gp.googlecode.com/svn/trunk
     * ac:  raytang10.4@gmail.com
     * pw:  mV8Dr2kS5ZM9
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();

        ResultSet rs = retrieveData("000000");

        String uid = "";
        String userName = "";
        String level = "";
        String money = "";
        String energy = "";

        try {
            rs.next();
            uid = rs.getString("UID");
            userName = rs.getString("userName");
            level = rs.getString("level");
            money = rs.getString("money");
            energy = String.valueOf(rs.getInt("energy"));
        } catch (SQLException ex) {
            Logger.getLogger(DisplayUserInfo.class.getName()).log(Level.SEVERE, null, ex);
        }

        out.println("<html>");
        out.println("<head>");
        out.println("<title>Servlet DisplayUserInfo</title>");

        //CSS 
        out.println("<style type=\"text/css\">");
        out.println("body{height:90%;}");
        out.println(".card{width:81px;height:81px}");
        out.println("#cardShow{width:270 px; height:360 px}");
        out.println("table{width:100%;}");
        out.println("#counter{float:right;}");
        out.println("h1{background-color:RED;color:WHITE;}");
        out.println("</style>");

        //Javascript
        out.println("<script type=\"text/javascript\">");
        out.println("function showIt(name){");
        out.println("   document.getElementById('cardShow').src = name;");
        out.println("   document.getElementById('cardShow').style.display = 'block';");
        out.println("}");
        out.println("function hideIt(){");
        out.println("   document.getElementById('cardShow').style.display='none';");
        out.println("}");
        out.println("</script>");      

        out.println("</head>");
        out.println("<body>");
        
        out.println("<h1>Player Information</h1>");
        
        try {
            out.println("<table>");
            out.println("<tr>");
            out.println(String.format("<th class='username'>UID: %s</th>", uid));
            out.println(String.format("<th class='username'>Name: %s</th>", userName));
            out.println("</tr>");
            out.println("</table>");

            out.println("<table>");
            out.println("<tr>");
            out.println(String.format("<th class='username'>Level: %s", level));
            out.println(String.format("<th class='username'>Money: %s", money));
            out.println("</tr>");
            out.println("</table>");

            String winPercent;
            try {
                winPercent = String.valueOf(rs.getInt("noOfWinning") / rs.getInt("totalGamePlayed")) + '%';
            } catch (Exception ex) {
                winPercent = "0%";
            }

            out.println(String.format("<p name='winPercent'>Win Percent: %s", winPercent));
            out.println(String.format("<p name='energy'>Energy: %s", energy));
            if (Integer.parseInt(energy) < 500) 
                printCounter(30000, out);
            //int count = countCard(uid);
            printTactics(out, uid);
            printCard(out, uid);
            out.println("<img src=\"\" id=\"cardShow\"></img>");


            out.println("</body>");
            out.println("</html>");
        } finally {
            out.close();
        }
    }

    private void printTactics(PrintWriter out, String uid){
        ResultSet rs;
        try {
            Context initCtx = new InitialContext();
            Context envCtx = (Context) initCtx.lookup("java:comp/env");
            DataSource ds = (DataSource) envCtx.lookup("jdbc/FootballManager");
            Connection con = ds.getConnection();
            Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
            String sql = String.format("SELECT * FROM Tactics INNER JOIN Customers_Tactics ON Customers_Tactics.name = Tactics.name AND UID = '%s'", uid);
            rs = stmt.executeQuery(sql);
            rs.next();
            // To-Do
            
        } catch (SQLException ex) {
            Logger.getLogger(DisplayUserInfo.class.getName()).log(Level.SEVERE, null, ex);
        } catch (NamingException ex) {
            Logger.getLogger(DisplayUserInfo.class.getName()).log(Level.SEVERE, null, ex);
        }
        
    }
    
    /*
    private int countCard(String uid) {
        int result = 0;
        ResultSet rs = getCards(uid);
        try {
            if (rs != null && rs.last()) {
                result = rs.getRow();
                rs.beforeFirst(); 
            }
        } catch (SQLException ex) {
            Logger.getLogger(DisplayUserInfo.class.getName()).log(Level.SEVERE, null, ex);
        }

        return result;
    }
    */
    
    private void printCard(PrintWriter out, String uid) {

        ResultSet rs = getCards(uid);
        int counter = 4;
        try {
            out.println("<p>");
            while (rs != null && rs.next()) {
                String playerName = rs.getString("name");
                String imageURL = PlayersEnum.getPlayerImageURLByName(playerName);
                String cardURL = PlayersEnum.getCardURLByName(playerName);
                //onmouseout=\"hideIt()\"
                out.println(String.format("<img src=\"%s\" name=\"%s\" class=\"card\" onmouseover=\"showIt(this.name)\" ></img>", imageURL, cardURL));
                counter--;
            }
            while(counter != 0){
                String playerName = "Empty";
                String imageURL = PlayersEnum.getPlayerImageURLByName(playerName);
                String cardURL = PlayersEnum.getCardURLByName(playerName);
                //onmouseout=\"hideIt()\"
                out.println(String.format("<img src=\"%s\" name=\"%s\" class=\"card\" onmouseover=\"showIt(this.name)\"></img>", imageURL, cardURL));
                counter--;
            }out.println("</p>");
            
        } catch (SQLException ex) {
            Logger.getLogger(DisplayUserInfo.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private ResultSet getCards(String uid) {
        try {
            Context initCtx = new InitialContext();
            Context envCtx = (Context) initCtx.lookup("java:comp/env");
            DataSource ds = (DataSource) envCtx.lookup("jdbc/FootballManager");
            Connection con = ds.getConnection();
            Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
            /*
             * select Player.name from Player Inner Join Customers_Players ON
             * Customers_Players.PlayerID = Player.PlayerID AND
             * Customers_Players.UID = 'uid'
             */
            String sql = String.format("SELECT Player.name FROM Player INNER JOIN Customers_Players ON Customers_Players.PlayerID = Player.PlayerID AND UID = '%s'", uid);
            ResultSet rs = stmt.executeQuery(sql);
            return rs;

        } catch (SQLException ex) {
            Logger.getLogger(DisplayUserInfo.class.getName()).log(Level.SEVERE, null, ex);
        } catch (NamingException ex) {
            Logger.getLogger(DisplayUserInfo.class.getName()).log(Level.SEVERE, null, ex);
        }
        return null;
    }

    private void printCounter(long finishTime, PrintWriter out) {
        int h, m, s;
        out.println("<form name=\"counter\" id=\"counter\">Complete on <input type=\"text\"  name=\"waitTime\" style=\"width:20px\"></form> ");
        out.println("<script type=\"text/javascript\"> ");
        finishTime = finishTime / 1000;
        finishTime *= 1000;
        out.println("var wTime=" + finishTime);
        out.println("document.counter.waitTime.value=" + (finishTime / 1000));
        out.println("function refresh(){");

        out.println("wTime-=1000");
        out.println("if (wTime>0){");
        out.println("   setTimeout(\"refresh()\",1000)");
        out.println("   document.counter.waitTime.value=wTime/1000");
        out.println("}else{");
        out.println(" window.location=\"userInfo\"");
        out.println("}");
        out.println("}");
        out.println("setTimeout(\"refresh()\",1000)");
        out.println("</script>");
    }

    private ResultSet retrieveData(String uid) {
        try {
            Context initCtx = new InitialContext();
            Context envCtx = (Context) initCtx.lookup("java:comp/env");
            DataSource ds = (DataSource) envCtx.lookup("jdbc/FootballManager");
            Connection con = ds.getConnection();
            Statement stmt = con.createStatement();
            String sql = String.format("SELECT * FROM CUSTOMERS WHERE uid='%s'", uid);
            return stmt.executeQuery(sql);
        } catch (SQLException ex) {
            Logger.getLogger(DisplayUserInfo.class.getName()).log(Level.SEVERE, null, ex);
        } catch (NamingException ex) {
            Logger.getLogger(DisplayUserInfo.class.getName()).log(Level.SEVERE, null, ex);
        }
        return null;
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
